package com.xilihui.xlh.core.util;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

/**
 * Created by WIN on 2017/2/16.
 */

public class TextStringUtils {

    /**
     * 设置textview部分颜色 可以设置多种颜色
     *
     * TextStringUtils.setSpanTextView(tv_message,"ysjjobssdfsadfsadfas",new TextStringUtils.SpanColorHolder(3,8,getResources().getColor(R.color.blue)),
     new TextStringUtils.SpanColorHolder(7,10,getResources().getColor(R.color.green)));
     * @param tv
     * @param str
     * @param colorHolders
     */
    public static void setSpanTextView(TextView tv, String str,
                                       SpanColorHolder... colorHolders) {

        if (colorHolders == null || colorHolders.length == 0) {
            tv.setText(str);
            return;
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(str);

        for (int i = 0; i < colorHolders.length; i++) {
            SpanColorHolder holder = colorHolders[i];
            ForegroundColorSpan span = new ForegroundColorSpan(holder.color);
            builder.setSpan(span, holder.start, holder.end,
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        tv.setText(builder);
        // ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
    }



    public static class SpanColorHolder {
        int start;
        int end;
        int color;

        public SpanColorHolder(int start, int end, int color) {
            super();
            this.start = start;
            this.end = end;
            this.color = color;
        }
    }



}
